In this tutorial, we provide two examples of formatting numbers with commas using Vue.js. In the first example, we format the number with a comma and two decimal places using the built-in method toLocaleString()
. In the second example, we utilize the Composition API to achieve the same functionality.
How to Add Commas to Numbers using Vue Js?
In the code below, we convert or format numbers with commas as thousand separators using a Vue js computed property inside a function, like ‘formattedNumber’, that returns the formatted value. If you want to edit your code or customize it, use the ‘TryIt’ editor and make it as per your preference
Vue Add Commas to Number
<script type="module">
const app = Vue.createApp({
data() {
return {
number: 1234567.899
};
},
computed: {
formattedNumber() {
const options = {
minimumFractionDigits: 2,
maximumFractionDigits: 2
};
return this.number.toLocaleString('en', options);
}
}
});
app.mount('#app');
</script>
Output of Vue Number Format Comma
Example 2: Vue 3 Number tolocalestring thousand separator
<script type="module">
const {createApp,ref,onMounted} = Vue;
createApp({
setup() {
const number = ref(1000000);
const formattedNumber = ref('');
onMounted(() => {
formatNumber();
});
const formatNumber = () => {
formattedNumber.value = number.value.toLocaleString();
};
return {
number,
formattedNumber
};
}
}).mount("#app");
</script>